<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>05_防抖-立即执行功能</title>
</head>
<body>

  
  <button>按钮</button>

  <input type="text">
  <button class="cancel">取消</button>

  <script>

    function debounce(fn, delay, immediate = false) {
      let timer = null;
      let isImmediate = true;
      const _debounce = function (...args) {
        if (timer) {
          clearTimeout(timer)
        }
        if (isImmediate && immediate) {
          fn.apply(this, args)
          isImmediate = false
        } else {
          timer = setTimeout(() => {
            // fn.apply(this, arguments) // this指向调用debounce函数的元素，arguments是事件对象
            fn.apply(this, args)
            timer = null // 清空timer，防止内存泄漏
            isImmediate = false
          }, delay)
        }
      }

      _debounce.cancel = function () {
        if (timer) {
          clearTimeout(timer)
          timer = null
          isImmediate = false
        }
      }

      return _debounce
    }

    // 3.防抖处理代码
    let counter = 1
    const inputEl = document.querySelector('input')
    const cancelBtn = document.querySelector(".cancel")
    const debounceFn = debounce(function (event) {
      console.log(`发送网络请求${counter++}:`, this, event)
    }, 3000, true)

    inputEl.oninput = debounceFn

    // 4.实现取消的功能
    cancelBtn.onclick = function() {
      debounceFn.cancel()
    }

  </script>
  
</body>
</html>